

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=dark>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/my-blog/img/fluid.png">
  <link rel="icon" href="/my-blog/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="木舟">
  <meta name="keywords" content="python Vue Test 测试开发 自动化测试">
  
    <meta name="description" content="前言  不管我们使用何种编程语言，在编写 脚本、工具、工程 时，都必不可少的会遇到异常情况。这种情况可能由以下场景触发的:  调用的第三方库、框架，使用中没有按照规范正确使用 数据源复杂，类型多样，无法第一时间确定 自己编写的框架，需要异常处理机制，来避免程序停止运行    所以在所有编程语言中，都会有异常处理机制，python也不例外。  掌握这种异常处理方式，会让你编写的程序更加符合自己的预期">
<meta property="og:type" content="article">
<meta property="og:title" content="try-except">
<meta property="og:url" content="https://walker_kwu.gitee.io/my-blog/2022/07/11/python/advanced/try-except/">
<meta property="og:site_name" content="My Blog">
<meta property="og:description" content="前言  不管我们使用何种编程语言，在编写 脚本、工具、工程 时，都必不可少的会遇到异常情况。这种情况可能由以下场景触发的:  调用的第三方库、框架，使用中没有按照规范正确使用 数据源复杂，类型多样，无法第一时间确定 自己编写的框架，需要异常处理机制，来避免程序停止运行    所以在所有编程语言中，都会有异常处理机制，python也不例外。  掌握这种异常处理方式，会让你编写的程序更加符合自己的预期">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2022-07-11T08:27:06.000Z">
<meta property="article:modified_time" content="2023-05-23T10:37:53.263Z">
<meta property="article:author" content="木舟">
<meta property="article:tag" content="测试开发">
<meta property="article:tag" content="Python进阶">
<meta name="twitter:card" content="summary_large_image">
  
  
    <meta name="referrer" content="no-referrer-when-downgrade">
  
  
  <title>try-except - My Blog</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/my-blog/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/my-blog/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/my-blog/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"walker_kwu.gitee.io","root":"/my-blog/","version":"1.9.2","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"left","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/my-blog/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/my-blog/js/utils.js" ></script>
  <script  src="/my-blog/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 6.2.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/my-blog/">
      <strong>木舟</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/my-blog/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="try-except"></span>
          
        </div>

        
          
  <div class="mt-3">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-author" aria-hidden="true"></i>
        木舟
      </span>
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2022-07-11 16:27" pubdate>
          2022年7月11日 下午
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          5.9k 字
        
      </span>
    

    

    
    
      
        <span id="busuanzi_container_page_pv" style="display: none">
          <i class="iconfont icon-eye" aria-hidden="true"></i>
          <span id="busuanzi_value_page_pv"></span> 次
        </span>
        
      
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="padding-left: 2rem; margin-right: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">try-except</h1>
            
              <p class="note note-info">
                
                  
                    本文最后更新于：2023年5月23日 晚上
                  
                
              </p>
            
            
              <div class="markdown-body">
                
                <h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p>  不管我们使用何种编程语言，在编写 <strong>脚本、工具、工程</strong> 时，都必不可少的会遇到异常情况。这种情况可能由以下场景触发的:</p>
<ul>
<li>调用的第三方库、框架，使用中没有按照规范正确使用</li>
<li>数据源复杂，类型多样，无法第一时间确定</li>
<li>自己编写的框架，需要异常处理机制，来避免程序停止运行</li>
</ul>
<p>  所以在<strong>所有</strong>编程语言中，都会有异常处理机制，<strong>python</strong>也不例外。<br>  掌握这种异常处理方式，会让你编写的程序更加符合自己的预期，有序的运行。<br>  本文会主要介绍基本语法，以及使用的场景，以及在<strong>测试开发</strong>领域中，比如<strong>编写框架</strong>，会用到的技巧。</p>
<h2 id="语法"><a href="#语法" class="headerlink" title="语法"></a>语法</h2><p>  注意：一旦使用 <strong>try</strong> ，后面就必须至少要使用 <strong>except/finally</strong> 其中一项</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-comment"># 语法</span><br><span class="hljs-comment"># 更多使用语法，可去菜鸟教程查看</span><br><span class="hljs-comment"># link：https://www.runoob.com/python/python-exceptions.html</span><br><span class="hljs-keyword">try</span>: <br>    <span class="hljs-string">&#x27;your code&#x27;</span><br><span class="hljs-keyword">except</span> Exception:<br>    <span class="hljs-built_in">print</span>(Exception)<br><span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> e: <span class="hljs-comment"># as 可以进行重命名</span><br>    <span class="hljs-built_in">print</span>(e)<br><span class="hljs-keyword">except</span>: <br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;捕捉除已知外的所有异常&quot;</span>)<br><span class="hljs-keyword">finally</span>:<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;不管怎么样，都必须要执行的代码&quot;</span>)<br><span class="hljs-keyword">else</span>:<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;如果没有异常发生才会执行的代码&quot;</span>)<br></code></pre></td></tr></table></figure>

<h2 id="工作原理"><a href="#工作原理" class="headerlink" title="工作原理"></a>工作原理</h2><p>  下文会有例子进行不同场景的说明</p>
<ul>
<li>程序执行到 <strong>try</strong> 关键字时，会将程序上下文进行标记，标记点为 <strong>try</strong> 的起始位置</li>
<li>如果<strong>try</strong>子句，也就是代码块，没有发生异常，如果有<strong>else</strong>，将会执行其子句</li>
<li>如果发生了异常，工作流会检索是否有<strong>except</strong>，采取优先处理机制（与if-elif类似），如果有捕捉到对应的异常，后续<strong>except</strong>将不会执行捕捉，结束整个工作流。</li>
<li>不管是否出现异常，如果有<strong>finally</strong>，都会执行其子句。</li>
</ul>
<h2 id="语法例子"><a href="#语法例子" class="headerlink" title="语法例子"></a>语法例子</h2><h3 id="场景一：发生异常，且不声明具体捕捉的异常"><a href="#场景一：发生异常，且不声明具体捕捉的异常" class="headerlink" title="场景一：发生异常，且不声明具体捕捉的异常"></a>场景一：发生异常，且不声明具体捕捉的异常</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><code class="hljs python">i = <span class="hljs-string">&#x27;abc&#x27;</span><br><br><span class="hljs-comment"># 自动触发异常，无法转化成整型</span><br><span class="hljs-keyword">try</span>:<br>    i = <span class="hljs-built_in">int</span>(i)<br><span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> e:<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;Error: <span class="hljs-subst">&#123;e&#125;</span>&quot;</span>)<br><br><span class="hljs-comment"># 运行结果：Error: invalid literal for int() with base 10: &#x27;abc&#x27;</span><br><br><br><span class="hljs-comment"># 手动触发触发异常</span><br><span class="hljs-keyword">try</span>:<br>    <span class="hljs-keyword">raise</span> <span class="hljs-comment"># 手动触发异常</span><br><span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> e:<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;Error: <span class="hljs-subst">&#123;e&#125;</span>&quot;</span>)<br><br><span class="hljs-comment"># 运行结果：Error: No active exception to reraise</span><br></code></pre></td></tr></table></figure>

<h3 id="场景二：无异常"><a href="#场景二：无异常" class="headerlink" title="场景二：无异常"></a>场景二：无异常</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><code class="hljs python">i = <span class="hljs-string">&#x27;abc&#x27;</span><br><br><span class="hljs-comment"># 无异常，执行else</span><br><span class="hljs-keyword">try</span>:<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;无异常&quot;</span>)<br><span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> e:<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;异常&quot;</span>)<br><span class="hljs-keyword">else</span>:<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;无异常执行&quot;</span>)<br><br><span class="hljs-comment"># 运行结果：</span><br><span class="hljs-comment"># 1. 无异常</span><br><span class="hljs-comment"># 2. 无异常执行</span><br><br><br><span class="hljs-comment"># 有异常，不执行else</span><br><span class="hljs-keyword">try</span>:<br>    i = <span class="hljs-built_in">int</span>(i)<br><span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> e:<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;Error: <span class="hljs-subst">&#123;e&#125;</span>&quot;</span>)<br><span class="hljs-keyword">else</span>:<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;无异常执行&quot;</span>)<br><br><span class="hljs-comment"># 运行结果：Error: invalid literal for int() with base 10: &#x27;abc&#x27;</span><br></code></pre></td></tr></table></figure>

<h3 id="场景三：异常捕捉优先处理机制"><a href="#场景三：异常捕捉优先处理机制" class="headerlink" title="场景三：异常捕捉优先处理机制"></a>场景三：异常捕捉优先处理机制</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">try</span>:<br>    <span class="hljs-keyword">raise</span> ValueError(<span class="hljs-string">&quot;手动触发 ValueError&quot;</span>)<br><span class="hljs-keyword">except</span> ValueError <span class="hljs-keyword">as</span> e:  <span class="hljs-comment"># 精确捕捉</span><br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;Error: <span class="hljs-subst">&#123;e&#125;</span>&quot;</span>)<br><span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> e:<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;上面捕捉到了，这里就不会再执行了&quot;</span>)<br><br><span class="hljs-comment"># 运行结果：Error: 手动触发 ValueError</span><br></code></pre></td></tr></table></figure>

<h3 id="场景四：finally"><a href="#场景四：finally" class="headerlink" title="场景四：finally"></a>场景四：finally</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-comment"># 常规用法</span><br><span class="hljs-keyword">try</span>:<br>    <span class="hljs-keyword">raise</span> ValueError(<span class="hljs-string">&quot;手动触发 ValueError&quot;</span>)<br><span class="hljs-keyword">except</span> ValueError <span class="hljs-keyword">as</span> e:  <span class="hljs-comment"># 精确捕捉</span><br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;Error: <span class="hljs-subst">&#123;e&#125;</span>&quot;</span>)<br><span class="hljs-keyword">finally</span>:<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;不管怎么样我都执行&quot;</span>)<br><br><span class="hljs-comment"># 即使是return，也必须遵守finally规则</span><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">test</span>():<br><br>    <span class="hljs-keyword">try</span>:<br>        <span class="hljs-keyword">return</span> <span class="hljs-number">1</span><br>    <span class="hljs-keyword">finally</span>:<br>        <span class="hljs-keyword">return</span> <span class="hljs-number">2</span><br><br>res = test()<br><span class="hljs-built_in">print</span>(res)<br><span class="hljs-comment"># 运行结果：2</span><br><br>f = <span class="hljs-built_in">open</span>()<br><br><span class="hljs-comment"># 文件关闭例子</span><br><span class="hljs-keyword">try</span>: <br>    <span class="hljs-string">&#x27;your code&#x27;</span><br><span class="hljs-keyword">finally</span>:<br>    f.close()<br></code></pre></td></tr></table></figure>

<p>针对场景四中的第二第三个例子，作者觉得需要进行一下特殊说明<br>先说第二个例子：<br>函数内如果调用<strong>return</strong>，正常情况下，会立即停止函数的运行，如果对<strong>finally</strong>机制不了解，会觉得会返回1。但是只要你用了finally，不管如何，都会执行finally的子句。<br>再说第三个例子：<br>在任何编程语言中，进行了文件打开的操作，就会在操作系统中开辟一个内存空间，用来缓存文件，如果不及时关闭，就可能会造成内存不够用的情况。<br>在 <em><strong>with</strong></em> 关键字不被人熟知的时候，文件操作常常会使用<strong>try-finally</strong>来进行文件处理和关闭。(关于with关键字的内容，本博客会有相关的文章进行介绍)</p>
<h2 id="如何自定义异常"><a href="#如何自定义异常" class="headerlink" title="如何自定义异常"></a>如何自定义异常</h2><p>我们编写自己的程序或者调用第三方库时，常常会遇到一些异常，这些异常往往会携带提示，帮助使用者进行错误修正以及规避。那我们能否定义属于自己框架的异常呢？答案肯定是可以的。<br>所有的异常本质上都是一个类，需要继承 <strong>Exception</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">class</span> <span class="hljs-title class_">customException</span>(<span class="hljs-title class_ inherited__">Exception</span>):<br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params">self</span>):<br>        ...<br>    <br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">__str__</span>(<span class="hljs-params">self</span>):<br>        ...<br></code></pre></td></tr></table></figure>
<p>__init__可写可不写，加上__init__可以传递参数，可以通过参数来定制生成一些动态的msg<br>__str__是类的魔法方法，当类拥有该魔法方法后，可以控制类<strong>实例化</strong>后返回的文本</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">class</span> <span class="hljs-title class_">customException</span>(<span class="hljs-title class_ inherited__">Exception</span>):<br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params">self</span>):<br>        ...<br>    <br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">__str__</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;这是一个异常&quot;</span><br><br><span class="hljs-built_in">print</span>(customException())<br><br><span class="hljs-comment"># 运行结果：这是一个异常</span><br></code></pre></td></tr></table></figure>

<h3 id="一个示例"><a href="#一个示例" class="headerlink" title="一个示例"></a>一个示例</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">class</span> <span class="hljs-title class_">customException</span>(<span class="hljs-title class_ inherited__">Exception</span>):<br>    error_type_dict = &#123;<br>        <span class="hljs-string">&#x27;action&#x27;</span>: &#123;<span class="hljs-string">&#x27;text&#x27;</span>: <span class="hljs-string">&#x27;操作类错误&#x27;</span>&#125;,<br>        <span class="hljs-string">&#x27;arg&#x27;</span>: &#123;<span class="hljs-string">&#x27;text&#x27;</span>: <span class="hljs-string">&#x27;参数类错误&#x27;</span>&#125;<br>    &#125;<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params">self, error_type, argList</span>):<br>        self.error_type = error_type<br>        self.argList = argList<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">__str__</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-keyword">return</span> <span class="hljs-string">f&quot;报错啦！！错误类型: <span class="hljs-subst">&#123;self.error_type_dict[self.error_type]&#125;</span>  |  输入参数: <span class="hljs-subst">&#123;self.argList&#125;</span>&quot;</span><br><br><br><span class="hljs-keyword">try</span>:<br>    <span class="hljs-keyword">raise</span> customException(<br>        error_type=<span class="hljs-string">&#x27;action&#x27;</span>,<br>        argList=[<span class="hljs-string">&#x27;arg1&#x27;</span>]<br>    )<br><span class="hljs-keyword">except</span> customException <span class="hljs-keyword">as</span> e:<br>    <span class="hljs-built_in">print</span>(e)<br><br><span class="hljs-comment"># 运行结果：报错啦！！错误类型: &#123;&#x27;text&#x27;: &#x27;操作类错误&#x27;&#125;  |  输入参数: [&#x27;arg1&#x27;]</span><br></code></pre></td></tr></table></figure>

<h2 id="应用场景"><a href="#应用场景" class="headerlink" title="应用场景"></a>应用场景</h2><p>以作者之前写过的<strong>接口自动化框架</strong>限制规范举例</p>
<h3 id="限制举例"><a href="#限制举例" class="headerlink" title="限制举例"></a>限制举例</h3><p>公司业务接口只会涉及到<em><strong>post/get</strong></em>，两种接口请求方式。所以我在框架中进行规范限制，即：<br><strong>用例文件的接口请求方式 【Method】 只允许 【get/post】</strong></p>
<h3 id="代码举例"><a href="#代码举例" class="headerlink" title="代码举例"></a>代码举例</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><code class="hljs python">standard = [<br>    <span class="hljs-string">&#x27;GET&#x27;</span>,<br>    <span class="hljs-string">&#x27;POST&#x27;</span><br>]<br><br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">MethodException</span>(<span class="hljs-title class_ inherited__">Exception</span>):<br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params">self, method, case=<span class="hljs-literal">None</span></span>):<br>        self.method = method<br>        self.case = case<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">__str__</span>(<span class="hljs-params">self</span>):<br>        msg = <span class="hljs-string">f&quot;请求方式错误, 请求方式: <span class="hljs-subst">&#123;self.method&#125;</span>, 限制请求方式: <span class="hljs-subst">&#123;standard&#125;</span>&quot;</span><br>        <span class="hljs-keyword">if</span> self.case:  <span class="hljs-comment"># 控制是否打印用例详细信息，不传入参数【case】的时候不打印</span><br>            msg += <span class="hljs-string">f&quot;, 用例详细信息: <span class="hljs-subst">&#123;self.case&#125;</span>&quot;</span><br>        <span class="hljs-keyword">return</span> msg<br><br><span class="hljs-comment"># 这里是一条条用例</span><br>case_list = [<br>    &#123;<br>        <span class="hljs-string">&#x27;url&#x27;</span>: <span class="hljs-string">&#x27;www.baidu.com&#x27;</span>,<br>        <span class="hljs-string">&#x27;method&#x27;</span>: <span class="hljs-string">&#x27;get&#x27;</span>,<br>    &#125;,<br>    &#123;<br>        <span class="hljs-string">&#x27;url&#x27;</span>: <span class="hljs-string">&#x27;www.baidu.com&#x27;</span>,<br>        <span class="hljs-string">&#x27;method&#x27;</span>: <span class="hljs-string">&#x27;xxx&#x27;</span>,<br>    &#125;,<br>    &#123;<br>        <span class="hljs-string">&#x27;url&#x27;</span>: <span class="hljs-string">&#x27;www.baidu.com&#x27;</span>,<br>        <span class="hljs-string">&#x27;method&#x27;</span>: <span class="hljs-string">&#x27;post&#x27;</span>,<br>    &#125;,<br>]<br><br><span class="hljs-keyword">for</span> case <span class="hljs-keyword">in</span> case_list:<br>    <span class="hljs-keyword">try</span>:<br>        <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> case[<span class="hljs-string">&#x27;method&#x27;</span>].upper() <span class="hljs-keyword">in</span> standard:<br>            <span class="hljs-keyword">raise</span> MethodException(case[<span class="hljs-string">&#x27;method&#x27;</span>], case)<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;用例执行成功&quot;</span>)<br>    <span class="hljs-keyword">except</span> MethodException <span class="hljs-keyword">as</span> e:<br>        <span class="hljs-built_in">print</span>(e)<br>    <span class="hljs-keyword">finally</span>:<br>        <span class="hljs-string">&quot;这里可以记录结果&quot;</span><br><br><span class="hljs-comment"># 运行结果：</span><br><span class="hljs-comment"># 1. 用例执行成功</span><br><span class="hljs-comment"># 2. 请求方式错误, 请求方式: xxx, 限制请求方式: [&#x27;GET&#x27;, &#x27;POST&#x27;], 用例详细信息: &#123;&#x27;url&#x27;: &#x27;www.baidu.com&#x27;, &#x27;method&#x27;: &#x27;xxx&#x27;&#125;</span><br><span class="hljs-comment"># 3. 用例执行成功</span><br></code></pre></td></tr></table></figure>

<p>如果我们不加<strong>try</strong>的话，在运行到第二条用例时，程序就会因为报错而终止。<br>将以上for循环代码块替换如下</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">for</span> case <span class="hljs-keyword">in</span> case_list:<br>    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> case[<span class="hljs-string">&#x27;method&#x27;</span>].upper() <span class="hljs-keyword">in</span> standard:<br>        <span class="hljs-keyword">raise</span> MethodException(case[<span class="hljs-string">&#x27;method&#x27;</span>], case)<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;用例执行成功&quot;</span>)<br><br><span class="hljs-comment"># 运行结果：</span><br><span class="hljs-string">&quot;&quot;&quot;</span><br><span class="hljs-string">用例执行成功</span><br><span class="hljs-string">Traceback (most recent call last):</span><br><span class="hljs-string">  File &quot;C:/Users/sasa/Desktop/test/update.py&quot;, line 36, in &lt;module&gt;</span><br><span class="hljs-string">    raise MethodException(case[&#x27;method&#x27;], case)</span><br><span class="hljs-string">__main__.MethodException: 请求方式错误, 请求方式: xxx, 限制请求方式: [&#x27;GET&#x27;, &#x27;POST&#x27;], 用例详细信息: &#123;&#x27;url&#x27;: &#x27;www.baidu.com&#x27;, &#x27;method&#x27;: &#x27;xxx&#x27;&#125;</span><br><span class="hljs-string">&quot;&quot;&quot;</span><br></code></pre></td></tr></table></figure>
<p>可以看得出来，第三条用例并没有运行</p>
<h3 id="可能会有的疑问"><a href="#可能会有的疑问" class="headerlink" title="可能会有的疑问"></a>可能会有的疑问</h3><p>有读者可能会对上面的例子产生疑问：<br><strong>我不通过异常，我也能控制输出啊。那为什么我要通过异常的方式呢？</strong><br>异常处理机制，是属于<strong>全方面</strong>捕捉。<br>也就是说，在我用异常处理包裹的子句，不管调用层级多深，只要用异常，就能够马上捕捉，做出对应的处理。<br>因为在我们实际编写程序中，往往一个工程会进行各种调用，但是入口只有一个。<br>只要我们在入口处进行异常处理的包裹，我们就能在一个地方去处理我们程序内部各个地方所触发的异常。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">main</span>():<br>    <span class="hljs-string">&quot;&quot;&quot;</span><br><span class="hljs-string">    程序运行入口函数</span><br><span class="hljs-string">    :return:</span><br><span class="hljs-string">    &quot;&quot;&quot;</span><br>    ...<br><br><br><span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">&#x27;__main__&#x27;</span>:<br>    <span class="hljs-keyword">try</span>:  <span class="hljs-comment"># 在函数入口进行捕捉</span><br>        main()<br>    <span class="hljs-comment"># 捕捉程序内部将会发生的一些错误</span><br>    <span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> e1:<br>        <span class="hljs-built_in">print</span>(e1)<br>    <span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> e2:<br>        <span class="hljs-built_in">print</span>(e2)<br>    <span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> e3:<br>        <span class="hljs-built_in">print</span>(e3)<br>    <span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> e4:<br>        <span class="hljs-built_in">print</span>(e4)<br>    <span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> e5:<br>        <span class="hljs-built_in">print</span>(e5)<br></code></pre></td></tr></table></figure>

<p>上面就是一个很直观的例子。</p>
<h2 id="最后"><a href="#最后" class="headerlink" title="最后"></a>最后</h2><p>异常捕捉是编程语言中一个很重要的知识点，关乎到你的代码设计<strong>合理性</strong>以及<strong>易用性</strong>。<br>你可以使用它进行工具、框架类项目的使用规范提示，也可以拿来做大型项目的第三方数据源的复杂场景处理。<br>但是异常处理要遵循一个原则：<br>不可遍地都是<strong>try-except</strong>，如果一定要用，就必须在程序调试后，在<strong>except</strong>进行精确的异常捕捉。<br>如果遍地都是<strong>try-except</strong>，你的程序会逐渐变得不可控，可能会出现十分难以排查的bug。</p>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/my-blog/categories/python/" class="category-chain-item">python</a>
  
  
    <span>></span>
    
  <a href="/my-blog/categories/python/Python%E8%BF%9B%E9%98%B6/" class="category-chain-item">Python进阶</a>
  
  

  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/my-blog/tags/%E6%B5%8B%E8%AF%95%E5%BC%80%E5%8F%91/">#测试开发</a>
      
        <a href="/my-blog/tags/Python%E8%BF%9B%E9%98%B6/">#Python进阶</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>try-except</div>
      <div>https://walker_kwu.gitee.io/my-blog/2022/07/11/python/advanced/try-except/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>木舟</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2022年7月11日</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>更新于</div>
          <div>2023年5月23日</div>
        </div>
      
      <div class="license-meta-item">
        <div>许可协议</div>
        <div>
          
            
            
              <a target="_blank" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">
              <span class="hint--top hint--rounded" aria-label="BY - 署名">
                <i class="iconfont icon-by"></i>
              </span>
              </a>
            
              <a target="_blank" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">
              <span class="hint--top hint--rounded" aria-label="NC - 非商业性使用">
                <i class="iconfont icon-nc"></i>
              </span>
              </a>
            
              <a target="_blank" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">
              <span class="hint--top hint--rounded" aria-label="SA - 相同方式共享">
                <i class="iconfont icon-sa"></i>
              </span>
              </a>
            
          
        </div>
      </div>
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/my-blog/2022/07/11/top/" title="写在前面">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">写在前面</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <span>By 木舟</span> <i class="iconfont icon-love"></i> 
    </div>
  
  
    <div class="statistics">
  
  

  
    
      <span id="busuanzi_container_site_pv" style="display: none">
        总访问量 
        <span id="busuanzi_value_site_pv"></span>
         次
      </span>
    
    
      <span id="busuanzi_container_site_uv" style="display: none">
        总访客数 
        <span id="busuanzi_value_site_uv"></span>
         人
      </span>
    
    
  
</div>

  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/my-blog/js/events.js" ></script>
<script  src="/my-blog/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/my-blog/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      headingSelector : CONFIG.toc.headingSelector || 'h1,h2,h3,h4,h5,h6',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      collapseDepth   : CONFIG.toc.collapseDepth || 0,
      scrollSmooth    : true,
      headingsOffset  : -boardTop
    });
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.10/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/my-blog/js/local-search.js" ></script>

  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/my-blog/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
